const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const mapMerge = function(src, tar) {
  for(key in tar){
    src[key] = tar[key]
  }
  return src
}

const chooseImages = function(obj) {
  var callback = obj.success
  obj.success = function(res) {
    var imgs = res.tempFilePaths
    var count = 0
    var totalCount = res.tempFilePaths.length
    console.log(totalCount)
    function addImg(index, img) {
      imgs[index] = img
      count++
      if (count == totalCount) {
        callback(imgs)
      }
    }

    function getImgInfo(index, src) {
      wx.getImageInfo({
        src: src,
        success: function (img) {
          addImg(index, {
            url: img.path,
            width: img.width,
            height: img.height
          })
        }
      })
    }

    for (var i = 0; i < res.tempFilePaths.length; i++) {
      getImgInfo(i, res.tempFilePaths[i])
    }
  }
  wx.chooseImage(obj)
}

module.exports = {
  formatTime: formatTime,
  mapMerge: mapMerge,
  chooseImages: chooseImages
}
